/**
 * Copyright 2011 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jku.mobcomp;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jku.mobcomp.helper.Const;


import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.Transform;

/**
 * This servlet responds to the request for getting an image
 * 
 * 
 */
@SuppressWarnings("serial")
public class ImageServlet extends BaseServlet {

  private static final Logger logger = Logger.getLogger(ImageServlet.class.getCanonicalName());
  /**
   * Get the image as binary
   */

  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
	super.doGet(req, resp);
    logger.log(Level.INFO, "Obtaining Image");
    String pathInfo = req.getPathInfo();       // z.B. /large_12345.jpg
    String requestUri = req.getRequestURI();    // z.B. /imageline/large_12345.jpg
    resp.addHeader("Pragma",  "public");
	resp.setHeader("Cache-Control", "max-age=86400");
	
	String boulderKeyId = Boulder.extractKeyIdFromPathInfo(pathInfo);
	boolean imageIsLine = Boulder.extractIsLineFromRequestUri(requestUri);
	String imageSize = Boulder.extractImageSizeFromPathInfo(pathInfo);
	String imageType = Boulder.getImageType(boulderKeyId);
    byte[] imageByte = Boulder.getImage(boulderKeyId, imageSize, imageIsLine);
    
    if (imageByte==null) {
		imageByte = new String("leer!").getBytes();
		imageType = null;
	    logger.log(Level.INFO, "Image- no Picture: ");
	}
	
	if (imageType!=null && !imageType.isEmpty() ) {
		resp.setHeader("Content-Type", "image/" + imageType); 
	}
	else{
		resp.setHeader("Content-Type", "text/html"); 
	}

    
     
    resp.getOutputStream().write(imageByte);
  }



}